package com.wy.utils;


import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: tracy
 * @Date: 2018/9/12 15:20
 * @Description:
 */
public class FileUtil {
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

//    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
//        ExportParams exportParams = new ExportParams(title, sheetName);
//        exportParams.setCreateHeadRows(isCreateHeader);
//        defaultExport(list, pojoClass, fileName, response, exportParams);
//
//    }
//    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
//        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
//    }
//    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
//        defaultExport(list, fileName, response);
//    }
//
//    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
//        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
//        if (workbook != null);
//        downLoadExcel(fileName, response, workbook);
//    }
//
//    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
//        try {
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.setHeader("Content-Disposition",
//                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//            workbook.write(response.getOutputStream());
//        } catch (IOException e) {
////            throw new NormalException(e.getMessage());
//        }
//    }
//    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
//        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF.toString());
//        if (workbook != null);
//        downLoadExcel(fileName, response, workbook);
//    }
//
//    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
//        if (StringUtils.isBlank(filePath)){
//            return null;
//        }
//        ImportParams params = new ImportParams();
//        params.setTitleRows(titleRows);
//        params.setHeadRows(headerRows);
//        List<T> list = null;
//        try {
//            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
//        }catch (NoSuchElementException e){
////            throw new NormalException("模板不能为空");
//        } catch (Exception e) {
//            e.printStackTrace();
////            throw new NormalException(e.getMessage());
//        }
//        return list;
//    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
//            throw new NormalException("excel文件不能为空");
        } catch (Exception e) {
//            throw new NormalException(e.getMessage());
        }
        return list;
    }

    //判断excel中是否有重复行

    /**
     *
     * @param mfile 导入的excel
     * @param column 判断的重复数据的列数，比如说是第三列，则column=2
     * @param ignoreRows 需要忽略的表头行数，默认为1行
     * @return
     */
    public static Map<String,String> judgeRepeatExcel(MultipartFile mfile,int column,int ignoreRows){
        HashMap<String,String> map=new HashMap<String,String>();
        HashMap<String,String> tmap=new HashMap<String,String>();
        String path =  ClassUtils.getDefaultClassLoader().getResource("").getPath();
        File file = new File(path+"temp.xls");
        //File file = (File)mfile;
        try {
            if(!file.exists()){
                file.createNewFile();
            }
            FileUtils.copyInputStreamToFile(mfile.getInputStream(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(column>=0&&file.exists()){
	   /*实现excle的兼容读取*/
            Workbook wb = null;
            try {
                wb = new XSSFWorkbook(new FileInputStream(file));
            } catch (Exception ex) {
                try {
                    wb= new HSSFWorkbook(new POIFSFileSystem(new BufferedInputStream(new FileInputStream(file))));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } //兼容读取设置结束
            Cell cell = null;
            System.out.println("本Excel总共有"+wb.getNumberOfSheets()+" 个Sheet 。");
            for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
                //循环所有的sheet,一个excle中可能有多个sheet

                Sheet sheet = wb.getSheetAt(sheetIndex);
                int firstRowNum = sheet.getFirstRowNum();
                int lastRowNum = sheet.getLastRowNum();

                firstRowNum=firstRowNum>ignoreRows?firstRowNum:ignoreRows;
                Row row = null;
                for (int i = firstRowNum; i <= lastRowNum; i++) {
                    row = sheet.getRow(i);          //取得第i行
                    cell = row.getCell(column);        //取得i行的第column列
                    String value ="";//保存i行的第column列的值
                    if (cell != null) {
                        switch (cell.getCellType()) {
                            case HSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue();
                                break;
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    Date date = cell.getDateCellValue();
                                    if (date != null) {
                                        value = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date);
                                    } else {
                                        value = "";
                                    }
                                } else {
                                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                                }
                                break;
                            case HSSFCell.CELL_TYPE_FORMULA:
                                // 导入时如果为公式生成的数据则无值
                                if (!cell.getStringCellValue().equals("")) {
                                    value = cell.getStringCellValue();
                                } else {
                                    value = cell.getNumericCellValue() + "";
                                }
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value = "";
                                break;
                            case HSSFCell.CELL_TYPE_BOOLEAN:
                                value = (cell.getBooleanCellValue() == true ? "Y": "N");
                                break;
                            default:
                                value = "";
                        }

                    }
			        /*在excel中，计数是从0开始的，为了使结果与Excel中显示的行数保持一致，让行数newNum=为（i+1）
			         */
                    int newNum=i+1;
                    if(map.containsKey(value)){//如果Map集合中包含指定的键名，则返回true；否则返回false。
                        String lineNum=map.get(value);//拿到先前保存的行号
                        //System.out.println("先前保存的行号value="+value+" lineNum="+lineNum);
                        if(tmap.containsKey(value)){
                            String str=tmap.get(value);//拿到先前保存的所有行号记录
                            tmap.put(value, str+" ,"+newNum);//更新后，显示效果：——》行重复：在第 2 ，3 , 5
                        }else{
                            tmap.put(value, "重复：行数位于第  "+lineNum+" ,"+newNum);//最后显示效果：——》行重复：在第 2 ，3
                        }
                    }
                    map.put(value, newNum+"");//把i行的第column列的值与行号保存到map中
                }
                Iterator<Map.Entry<String, String>> it=tmap.entrySet().iterator();
                System.out.println("本Excel总共有"+wb.getNumberOfSheets()+" 个Sheet,第 "+(sheetIndex+1)+" 个Sheet中：");
                while(it.hasNext()){
                    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
                    System.out.println("字段："+entry.getKey()+" "+entry.getValue());
                }

            }

            file.delete();
            return tmap ;
        }else{
            System.out.println("file为空？？？");
            return tmap ;
        }


    }



    /**
     * 转移文件
     * @param fileName 源文件路径
     * @param targetPath 目标文件夹路径
     * @param realName 目标文件名，不含路径
     * @return
     */
    public static String moveFilePath(String fileName,String targetPath,String realName){
        String path = "";
        File source = new File(fileName);
        File target = new File(targetPath);
        if(!source.exists()||source.isDirectory()){
            logger.error("源文件不存在或是一个文件夹："+ fileName);
            return path;
        }
        if(target.isFile()){
            logger.error("请填写正确目标文件路径："+ targetPath);
            return path;
        }
        if(!target.exists())
            target.mkdirs();
        boolean flag = false;
        File targetFile = new File(target + File.separator + realName);

        if(targetFile.exists()) {
            targetFile.delete();
        }
        if (source.renameTo(targetFile)){
            flag = true;
        }else{
            logger.error("文件转移失败，源文件："+ fileName+",目标文件路径："+targetPath);
        }
        return flag ? realName : "";
    }

    /**
     * 图片格式转换
     * @param srcFileName 源文件名称
     * @param tarPath 目标文件路径
     * @param suffix 目标文件的后缀，jpg\png等
     */
    public static void conversion(String srcFileName,String tarPath,String suffix){
        String srcName = "";
        BufferedImage bim = null;
        boolean isImage = true;
        try {
            File src = new File(srcFileName);
            srcName = src.getName();
            String[] names = srcName.split("\\.");
            if(names.length == 2){
                try{
                    bim = ImageIO.read(src);
                    if(bim == null){
                        isImage = false;
                    }
                }
                catch (IOException ex){
                    isImage = false;
                }
                if(isImage){
                    //if(!names[1].equals(suffix)){
                    File targetPath = new File(tarPath);
                    if(targetPath.isFile())
                        //logger.error("请填写正确目标文件路径："+ targetPath);
                        return;
                    if(!targetPath.exists())
                        targetPath.mkdirs();
                    File tarFile = new File(tarPath + File.separator + names[0] + "." + suffix);

                    ImageIO.write(bim, suffix, tarFile);
                    // }
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断文件是否是图片文件
     * @param fileName
     * @return
     */
    public static boolean isImage(String fileName){
        BufferedImage bim = null;
        boolean isImage = true;
        try{
            bim = ImageIO.read(new File(fileName));
            if(bim == null){
                isImage = false;
            }
        }
        catch (IOException ex){
            isImage = false;
        }
        return isImage;
    }

    /**
     * 转换文件夹下图片
     * @param path
     * @param targetPath
     * @param suffix
     */
    public static void conversionPath(String path,String targetPath,String suffix) {
        boolean flag = false;
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                FileUtil.conversion(tempList[i].getAbsolutePath(),targetPath,suffix);
            }
            if (tempList[i].isDirectory()) {
                conversionPath(tempList[i].getAbsolutePath(),targetPath,suffix);
            }
        }
    }

    public static String getPicName(String url) {
        if(StringUtils.isEmpty(url)) {
            return "";
        }
        try {
            return url.substring(url.lastIndexOf("/") + 1, url.length());
        }catch (Exception ex) {
            return "";
        }
    }

    public static List<String> getName(String path){
        File file = new File(path);
        File[] tempList = file.listFiles();
        List<String> temp = new ArrayList<>();
        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                String[] a = tempList[i].toString().substring(tempList[i].toString().lastIndexOf(File.separator)+1,tempList[i].toString().length()).split("#M");
                if(a.length >1)
                    temp.add(a[1]);
            }
        }
        return temp;

    }


    public static String getFileName(String url) {
        if(StringUtils.isEmpty(url)){
            return "";
        }
        return url.substring(url.lastIndexOf("/")+1,url.length());


    }

    public static void main(String[] args) {
//        conversionPath("d:\\test\\img","d:\\test\\img1","jpg");
//        String url = "http://128.2.2.1:90/sss/a.jpg";
//        System.out.println(url.substring(url.lastIndexOf("/")+1,url.length()));

//        FileUtil.conversionPath("d:\\test\\p1","d:\\test\\p2","jpg");
        System.out.println(getFileName(""));


    }

}
